package com.pu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.pu.constant.StatusConstant;
import com.pu.context.BaseContext;
import com.pu.dto.SetmealDTO;
import com.pu.dto.SetmealPageQueryDTO;
import com.pu.entity.Dish;
import com.pu.entity.Setmeal;
import com.pu.entity.SetmealDish;
import com.pu.exception.DeletionNotAllowedException;
import com.pu.exception.SetmealEnableFailedException;
import com.pu.mapper.DishMapper;
import com.pu.mapper.SetmealDishMapper;
import com.pu.mapper.SetmealMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pu.result.PageResult;
import com.pu.service.DishService;
import com.pu.service.SetmealService;
import com.pu.vo.DishItemVO;
import com.pu.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pu.constant.MessageConstant;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author Yusc
 * @Date 2023/10/28 17:34
 * @Version
 * @Description 套餐管理业务层实现
 **/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * @param setmealDTO setmealDTO
     * @auther: Yusc
     * @date 2023/10/28 17:42
     * @Description 新增套餐，同时需要保存套餐和菜品的关联关系
     */
    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal); //属性拷贝
        setmeal.setCreateTime(LocalDateTime.now());    //创建时间
        setmeal.setUpdateTime(LocalDateTime.now());    //修改时间
        setmeal.setCreateUser(BaseContext.getCurrentId()); //创建人id
        setmeal.setUpdateUser(BaseContext.getCurrentId()); //修改人id

        //向套餐表插入数据
        setmealMapper.insert(setmeal);

        //获取生成的套餐id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        //保存套餐和菜品的关联关系
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * @param setmealPageQueryDTO
     * @auther: Yusc
     * @date 2023/10/28 20:24
     * @Description 分页条件查询
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        int pageNum = setmealPageQueryDTO.getPage();        //页码
        int pageSize = setmealPageQueryDTO.getPageSize();   //每页大小

        PageHelper.startPage(pageNum, pageSize);    //开始分页
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @param ids
     * @auther: Yusc
     * @date 2023/10/28 20:57
     * @Description 批量删除套餐
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id -> {
            Setmeal setmeal = setmealMapper.selectById(id);
            // 判断套餐是否启用，启用则无法删除
            if (StatusConstant.ENABLE.equals(setmeal.getStatus())) {
                //起售中的套餐不能删除
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });

        // 1、删除套餐表中的数据
        setmealMapper.deleteBatchIds(ids);

        // 2.1、构造删除条件
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<SetmealDish>()
                .in(SetmealDish::getSetmealId, ids);
        // 2.2、删除套餐菜品关系表中的数据
        setmealDishMapper.delete(wrapper);
    }

    /**
     * @param id
     * @auther: Yusc
     * @date 2023/10/28 22:26
     * @Description 根据id查询套餐和套餐菜品关系
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        // 1、根据id查套餐
        Setmeal setmeal = setmealMapper.selectById(id);
        // 2.1、构造查询套餐菜品条件
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId, id);
        // 2.1、根据id查套餐菜品
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(wrapper);

        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);   //属性拷贝
        setmealVO.setSetmealDishes(setmealDishes);  // 设置套餐菜品

        return setmealVO;
    }

    /**
     * @param setmealDTO
     * @auther: Yusc
     * @date 2023/10/28 22:35
     * @Description 修改套餐
     */
    @Override
    @Transactional  // 应该要操作两个表，所以开启事务
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);  // 属性拷贝
        setmeal.setUpdateUser(BaseContext.getCurrentId());  //更新人id
        setmeal.setUpdateTime(LocalDateTime.now()); //更新时间

        // 1.1、构造修改条件
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getId, setmeal.getId());
        //1、修改套餐表，执行update
        setmealMapper.update(setmeal, wrapper);

        //获取套餐id
        Long setmealId = setmealDTO.getId();

        // 2.1 构造删除条件
        LambdaQueryWrapper<SetmealDish> deleteWrapper = new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId, setmealId);
        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.delete(deleteWrapper);

        //3、获取套餐菜品数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);    //修改id
        });

        //4、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.insertBatch(setmealDishes);
    }

    /**
     * @param status 起售状态
     * @param id     分类id
     * @auther: Yusc
     * @date 2023/10/28 22:45
     * @Description 套餐的起售停售
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 判断套餐中是否有停售的菜品，如果有则无法起售
        if (Objects.equals(status, StatusConstant.ENABLE)) {
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            List<Dish> dishList = dishMapper.getBySetmealId(id);    //根据分类id查询菜品
            if (dishList != null && !dishList.isEmpty()) {  //  判断套餐内是否有停售菜品
                dishList.forEach(dish -> {
                    if (StatusConstant.DISABLE.equals(dish.getStatus())) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        // 构建对象
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        // 更新
        lambdaUpdate().eq(Setmeal::getId, setmeal.getId())
                .update(setmeal);
    }

    /**
     * @param id 套餐id
     * @auther: Yusc
     * @date 2023/10/31 19:41
     * @Description 根据套餐id查询包含的菜品列表
     */
    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }


}
